package com.tmpt.controller.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.tmpt.utils.WebUtils;

/**
 *ip filter web.xml configuration method
 *<!-- ip filter -->
  <filter>
  	<filter-name>systemFilter</filter-name>
  	<filter-class>com.wuxiaoyong.filter.IpFilter</filter-class>
  	<init-param>
  		<param-name>ip1</param-name>
  		<param-value>192.168.200.8</param-value>
  	</init-param>
  	<init-param>
  		<param-name>ip2</param-name>
  		<param-value>192.168.200.9</param-value>
  	</init-param>
  </filter>
  <filter-mapping>
  	<filter-name>systemFilter</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>
 * @author pay
 *
 */
public class IpFilter implements Filter{
	private Logger log = Logger.getLogger(this.getClass());
	private Set<String> allowedIpList = new HashSet<String>();
	
	public void init(FilterConfig cfg) throws ServletException {
		Enumeration<String> ipEnum = cfg.getInitParameterNames();
		while(ipEnum.hasMoreElements()){
			String ipKey = ipEnum.nextElement();
			String ip = cfg.getInitParameter(ipKey);
			allowedIpList.add(ip);
		}
	}
	
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
				
		HttpServletRequest request = (HttpServletRequest)arg0;
		HttpServletResponse response = (HttpServletResponse)arg1;

		String ip = WebUtils.getRealIp(request);// request.getRemoteHost();
		log.debug("ip:"+ip);
		
		if("0:0:0:0:0:0:0:1".equals(ip)){ //localhost访问时，打印的ip是这个
			arg2.doFilter(arg0, arg1);
			return;
		}
		if("localhost".equals(ip)){
			arg2.doFilter(arg0, arg1);
			return;
		}
		if("127.0.0.1".equals(ip)){
			arg2.doFilter(arg0, arg1);
			return;
		}
		if(allowedIpList.contains(ip)){
			arg2.doFilter(arg0, arg1);
			return;
		}
		
		PrintWriter out = response.getWriter();
		out.print("Illegel access , your ip is not in ip container which allows some ip to access. ");
		out.close();
	}
	
	public void destroy() {
		allowedIpList = null;
	}
	
}
